/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.sunspotworld;

import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.peripheral.IAccelerometer3D;
import java.io.IOException;
import java.util.Random;

/**
 *
 * @author seb
 */
public class SensorThread extends Thread {

    private Main main;
    private boolean running;
    private Game game;
    private IAccelerometer3D accelerometer = EDemoBoard.getInstance().getAccelerometer();
    
    SensorThread(Main main, Game game){
        this.main = main;
        this.game = game;
    }

    public void run() {
       
        System.out.println("Sensor Thread running!");

        //run as long as we have the potatoe!
        while (game.getHasPotatoe()) {

            //check if the endtime of the potato has been reached
            if (!game.isEndTime()) {
                game.isOut();
            }
            //keep looking at the accelormeter if mayThrowTime is reached
            if (game.isMayThrowTime()) {
                try {
                    double accelX = accelerometer.getAccelX();

                    if (accelX > 2 || accelX < -2) {    //versnelling groter dan 2 of -2

                        // System.out.println("pass @ speed " + accelX);

                        //nieuwe random maken, random een entry van de lijst met connecties pakken
                        Random r = new Random();
                        Connection con = (Connection) main.getConnections().elementAt((int) (r.nextDouble() * main.getConnections().size()));
                        long adress = con.getAdress();

                        //potato sturen naar het adres van de hierboven gevonden random connectie
                        main.sendConnectionMessage(game.getEndTime() + " ", adress);
                        System.out.println("verstuurd: " + game.getEndTime() + " " + adress);
                        game.setPotatoe(false);
                        game.display();
                    }
                } catch (IOException ex) {
                    System.err.println("Error @ SensorThread.java:run() - IOException!");
                    ex.printStackTrace();
                }
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }

        System.out.println("Yes!");

    }
}
